from django.shortcuts import render, redirect, reverse
from django.http.response import JsonResponse
from django.template.response import TemplateResponse

from utils.ansible2.inventory import Inventory
from utils.ansible2.runner import AdHocRunner, PlayBookRunner
from .models import *
from .forms import *
from utils.pagination import Pagination
import json
import datetime

# from django.forms.models import model_to_dict
# request.session["user"] = model_to_dict(user)

RESULT_MSG = {
    "status": 200,
    "msg": None
}


def login(request):
    if request.method == "POST":
        email = request.POST.get("email")
        password = request.POST.get("password")
        print("email=", email)
        print("pwd=", password)
        user = UserProfile.objects.filter(
            email=email,
            password=password
        ).first()
        print("user==", user)
        if user:
            RESULT_MSG["msg"] = "登录成功"
            RESULT_MSG["username"] = user.name
            RESULT_MSG["role"] = user.get_role_display()
            RESULT_MSG["department"] = user.department
            RESULT_MSG["phone"] = user.phone
            RESULT_MSG["email"] = user.email
            RESULT_MSG["id"] = user.pk

            sessionid = request.COOKIES.get("sessionid", None)

            print("cookie=", request.COOKIES)
            print("session=", request.session.get("userssstoken", None))
            print("session-username", request.session.get("username", None))
            if request.session.get("email", None) == email:
                # request.session.delete()
                # request.session.clear()  # 清空的是值
                request.session.flush()  # 键和值一起清空
                # del request.session['key']  # 删除指定数据

            request.session['username'] = user.name
            request.session['email'] = user.email
            request.session['role'] = user.role
            request.session['department'] = user.department
            request.session['phone'] = user.phone
            request.session['id'] = user.pk
            request.account = user
        else:
            RESULT_MSG["status"] = 402
            RESULT_MSG["msg"] = "账号或密码错误"
        return JsonResponse(RESULT_MSG)
    return render(request, "login.html")


########################################用户#################################################
def userList(request):
    userList = UserProfile.objects.all().order_by("pk")
    page = Pagination(request.GET.get('page', 1), userList.count(), request.GET.copy(), 10)
    return TemplateResponse(request, 'user/userlist.html', {
        'userList': userList[page.start:page.end],
        'page_html': page.page_html,
        "title": "用户列表"
    })


def userAdd(request):
    form = UserProfileForm()
    return render(request, "user/userAdd.html", {"form_obj": form, })


def userChange(request, id=0):
    user = UserProfile.objects.filter(pk=id).first()
    if request.method == "POST":
        form = UserProfileForm(request.POST, instance=user)
        if form.is_valid():
            form.save()
            return JsonResponse({"status": 0, "msg": "操作成功!!"})
        else:
            return JsonResponse({"status": 1, "msg": "操作失败:{}".format(form.errors)})
    form = UserProfileForm(instance=user)
    return render(request, "user/userAdd.html", {"form_obj": form, "pk": id})


def userDel(request, id=None):
    UserProfile.objects.filter(pk=id).delete()
    return JsonResponse({"status": 0, "msg": "操作成功"})


##########################################主机####################################################
def hostList(request):
    host = Host.objects.filter(pk=request.account.pk)
    page = Pagination(request.GET.get('page', 1), host.count(), request.GET.copy(), 10)
    return TemplateResponse(request, "host/hostList.html", {
        'hostList': host[page.start:page.end],
        'page_html': page.page_html,
        "title": "主机列表"
    })


def hostChange(request, id=0):
    host = Host.objects.filter(pk=id).first()
    form = HostForm(instance=host)
    if request.method == "POST":
        form = HostForm(request.POST, instance=host)
        if form.is_valid():
            print("ping=", host_ping(form.cleaned_data['hostip'], form.cleaned_data['ssh_port']))
            if not host_ping(form.cleaned_data['hostip'], form.cleaned_data['ssh_port']):
                return JsonResponse({"status": 1, "msg": "添加失败，失败原因：主机不可达，请检查网络或者ssh连接"})
            form.save()
            RESULT_MSG["status"] = 0
            RESULT_MSG["msg"] = "操作成功"
            return JsonResponse(RESULT_MSG)
        else:
            RESULT_MSG["status"] = 1
            RESULT_MSG["msg"] = "操作失败:{}".format(form.errors)
            return JsonResponse(RESULT_MSG)
    return render(request, "host/hostChange.html", {"form_obj": form, "pk": id})


def host_ping(hostip, ssh_port):
    '''
    测试主机是否可连接
    :param hostip:
    :param ssh_port:
    :return:
    '''
    host_data = [{
        "hostname": hostip,
        "ip": hostip,
        "port": ssh_port
    }]
    inventory = Inventory(host_data)  # 动态生成主机配置信息
    runner = AdHocRunner(inventory)
    tasks = [{
        "action": {"module": 'ping'}
    }]
    ret = runner.run(tasks)
    print(ret.results_raw)
    if not ret.results_raw['ok']:
        return False
    return True


def hostDel(request, id=0):
    Host.objects.filter(pk=id).delete()
    RESULT_MSG["status"] = 0
    RESULT_MSG["msg"] = "操作成功"
    return JsonResponse(RESULT_MSG)


########################################初始化########################################################
def initList(request):
    initList = Init.objects.all()
    page = Pagination(request.GET.get('page', 1), initList.count(), request.GET.copy(), 10)
    return TemplateResponse(request, "init/initList.html", {
        "initList": initList[page.start:page.end],
        'page_html': page.page_html,
        "title": "初始化列表"
    })


def initChange(request, id=0):
    init = Init.objects.filter(pk=id).first()
    form = InitForm(instance=init)
    if request.method == "POST":
        form = InitForm(request.POST, instance=init)
        if form.is_valid():
            form.instance.create_user = request.account
            form.save()
            RESULT_MSG["status"] = 0
            RESULT_MSG["msg"] = "操作成功"
            return JsonResponse(RESULT_MSG)
        else:
            RESULT_MSG["status"] = 1
            RESULT_MSG["msg"] = "操作失败:{}".format(form.errors)
            return JsonResponse(RESULT_MSG)
    return render(request, "init/initChange.html", {"form_obj": form, "pk": id})


def initDel(request, id=0):
    res = Init.objects.filter(pk=id).delete()
    print(res)
    if res:
        RESULT_MSG["status"] = 0
        RESULT_MSG["msg"] = "删除成功"
    else:
        RESULT_MSG["status"] = 1
        RESULT_MSG["msg"] = "删除失败"
    return JsonResponse(RESULT_MSG)


########################################################################################
'''
1.初始化机器
    ansible api 执行playbook
2.显示当前初始化的详情
    初始化的时间
    初始化的机器
    初始化的人
    初始化的结果
3. 项目管理
    boss字段可以显示user表的所有人
    dev_user 字段只能显示user表中职位是开发的
4. 实现项目的增删改查
'''


def projectList(request):
    pList = Project.objects.all()
    print("-->>", pList)
    page = Pagination(request.GET.get('page', 1), pList.count(), request.GET.copy(), 10)
    return TemplateResponse(request, "project/projectList.html", {
        "projectList": pList[page.start:page.end],
        'page_html': page.page_html,
        "title": "项目列表"
    })


def projectDetail(request, id=0):
    pList = Project.objects.filter(pk=id)
    print("-->>", pList)
    print("--id>>", id)
    return TemplateResponse(request, "project/projectDetail.html", {
        "projectList": pList,
        "title": "项目详情"
    })


def projectChange(request, id=0):
    p = Project.objects.filter(pk=id).first()
    form = ProjectForm(instance=p)
    if request.method == "POST":
        form = ProjectForm(request.POST, instance=p)
        if form.is_valid():
            form.save()
            RESULT_MSG["status"] = 0
            RESULT_MSG["msg"] = "操作成功"
            return JsonResponse(RESULT_MSG)
        else:
            RESULT_MSG["status"] = 1
            RESULT_MSG["msg"] = "操作失败:{}".format(form.errors)
            return JsonResponse(RESULT_MSG)
    return render(request, "project/projectChange.html", {"form_obj": form, "pk": id})


def projectDel(request, id=0):
    res = Project.objects.filter(pk=id).delete()
    if res:
        RESULT_MSG["status"] = 0
        RESULT_MSG["msg"] = "删除成功"
    else:
        RESULT_MSG["status"] = 1
        RESULT_MSG["msg"] = "删除失败"
    return JsonResponse(RESULT_MSG)


#########################################初始化日志信息#################################################
def initLogAdd(request):
    form = InitLogForm()
    if request.method == "POST":
        form = InitLogForm(request.POST)
        if form.is_valid():
            initresult = initlog(form.cleaned_data["hosts_list"], form.cleaned_data["init"].play_book)
            form.instance.result = initresult
            form.instance.user = request.account
            form.save()
            RESULT_MSG["status"] = 0
            RESULT_MSG["msg"] = "操作成功"
            return JsonResponse(RESULT_MSG)
        else:
            RESULT_MSG["status"] = 1
            RESULT_MSG["msg"] = "操作失败:{}".format(form.errors)
            return JsonResponse(RESULT_MSG)
    return render(request, "initLog/initLogAdd.html", {"form_obj": form, })


def initlog(hostlist, playbook):
    '''
     运行playbook
    :param hostlist:
    :param playbook:
    :return:
    '''
    host_data = [{"hostname": h.hostip, "ip": h.hostip, "port": h.ssh_port} for h in hostlist]
    print(host_data)
    print(playbook)
    inventory = Inventory(host_data)
    runner = PlayBookRunner(inventory).run(playbook)
    return runner


def initLogList(request, init_id=0):
    print("init_id=", init_id)
    init = Init.objects.filter(pk=init_id).first()
    logs = init.initlog_set.all()
    return render(request, "initLog/initLogList.html", {
        "logs": logs,
    })
